﻿using RuneMasterWin8.Core;
using RuneMasterWin8.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace RuneMasterWin8.Pages
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class MainPage : RuneMasterWin8.Common.LayoutAwarePage
    {
        public static MainPage Instance = null;

        public MainPage()
        {
            Instance = this;
            this.InitializeComponent();
            DisplayProperties.AutoRotationPreferences = DisplayOrientations.Landscape | DisplayOrientations.LandscapeFlipped;
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (!StageManager.Instance.IsLoaded)
            {
                ShowLoading();
                Task initTask = new Task(() =>
                {
                    StageManager.Instance.Init();
                });
                initTask.Start();
            }
            else
            {
                HideLoading();
            }

            if (StageManager.Instance.SavedGameRecord != null)
            {
                this.btnContinue.IsEnabled = true;
            }
            else
            {
                this.btnContinue.IsEnabled = false;
            }

            //音效
            if (StageManager.Instance.IsPlaySound)
            {
                AudioPlayHelper.PlayBackground();
                this.btnSoundOn.Visibility = Windows.UI.Xaml.Visibility.Visible;
                this.btnSoundOff.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else
            {
                this.btnSoundOn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                this.btnSoundOff.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }

            if (StageManager.Instance.IsDoNewUserTask)
            {
                this.btnNewUser.IsEnabled = false;
            }
            else
            {
                this.btnNewUser.IsEnabled = true;
            }

            GoToMarketComment();
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void btnContinue_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");

            // Continue
            if (StageManager.Instance.SavedGameRecord != null)
            {
                //设置关卡
                StageManager.Instance.CurrentGameMode = StageManager.Instance.SavedGameRecord.GameMode;
                StageManager.Instance.CurrentStageIndex = StageManager.Instance.SavedGameRecord.StageIndex;
                StageManager.Instance.CurrentSubStageIndex = StageManager.Instance.SavedGameRecord.SubStageIndex;
                StageManager.Instance.CurrentRestartChange = StageManager.Instance.SavedGameRecord.LeftLifeCount;

                //页面跳转
                this.Frame.Navigate(typeof(GamePage), false);
            }
        }

        private void btnNewGame_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            // Start New
            this.Frame.Navigate(typeof(ModeSelectPage));
        }

        private void btnMyScore_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            AudioPlayHelper.PlayEffectSound("button_click");
            // Show My Score View
            this.Frame.Navigate(typeof(ScorePage));
        }

        /// <summary>
        /// 历史记录加载完成
        /// </summary>
        internal async void StageManagerLoadComplete()
        {
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                HideLoading();

                if (StageManager.Instance.SavedGameRecord != null)
                {
                    this.btnContinue.IsEnabled = true;
                }
                else
                {
                    this.btnContinue.IsEnabled = false;
                }
            });
        }

        private void ShowLoading()
        {
            this.bdrLoding.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void HideLoading()
        {
            this.bdrLoding.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }

        private void btnSoundOn_Click(object sender, RoutedEventArgs e)
        {
            StageManager.Instance.IsPlaySound = false;
            AudioPlayHelper.StopBackground();
            this.btnSoundOn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            this.btnSoundOff.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }

        private void btnSoundOff_Click(object sender, RoutedEventArgs e)
        {
            StageManager.Instance.IsPlaySound = true;
            this.btnSoundOn.Visibility = Windows.UI.Xaml.Visibility.Visible;
            this.btnSoundOff.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            AudioPlayHelper.PlayBackground();
        }

        private async void GoToMarketComment()
        {
            if (StageManager.Instance.LaunchCount > 10 && !StageManager.Instance.IsCommented)
            {
                MessageDialog msg = new MessageDialog("喜欢我们的游戏吗？麻烦您去市场给我们一个五星好评吧，77Studio感谢您的支持！");
                msg.Commands.Add(new UICommand("立即去评分", async (command) =>
                {
                    Uri uri = new Uri("ms-windows-store:REVIEW?PFN=" + Package.Current.Id.FamilyName);
                    await Launcher.LaunchUriAsync(uri);
                    StageManager.Instance.IsCommented = true;
                }));
                msg.Commands.Add(new UICommand("取消", (command) =>
                {
                    StageManager.Instance.IsCommented = true;
                }));
                await msg.ShowAsync();
            }
        }

        private void btnNewUser_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(GiftPage));
        }
    }
}
